package com.nav.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLNode {
	public static final String TAG_ANCHOR = "a", TAG_DIV = "div", TAG_H3 = "h3", TAG_ROOT = "root", TAG_SPAN = "span", TAG_TEXT = "text";
	public static final String ATTR_CLASS = "class", ATTR_ID = "id", ATTR_VALUE = "value";
	String name;
	Map<String, String> attr = new HashMap<String, String>();
	List<XMLNode> body = new ArrayList<XMLNode>();
	public XMLNode(String name) {
		this.name = name;
	}
	public List<XMLNode> findTags(String tagName, String attrName, String attrValue) {
		List<XMLNode> tags = new ArrayList<XMLNode>();
		for(XMLNode tag : body) {
			if(tag.name.equalsIgnoreCase(tagName)) {
				String eAttrValue = tag.attr.get(attrName);
				if(eAttrValue != null && eAttrValue.equalsIgnoreCase(attrValue)) {
					tags.add(tag);
					continue;
				}
			}
			tags.addAll(tag.findTags(tagName, attrName, attrValue));
		}
		return tags;
	}
	public XMLNode findTag(String tagName, String attrName, String attrValue) {
		for(XMLNode tag : body) {
			if(tag.name.equalsIgnoreCase(tagName)) {
				String eAttrValue = tag.attr.get(attrName);
				if(eAttrValue != null && eAttrValue.equalsIgnoreCase(attrValue))
					return tag;
			}
			XMLNode foundTag = tag.findTag(tagName, attrName, attrValue);
			if(foundTag != null)
				return foundTag;
		}
		return null;
	}
	public XMLNode getTag(String tagName) {
		for(XMLNode tag : body)
			if(tag.name.equalsIgnoreCase(tagName))
				return tag;
		return null;
	}
	public XMLNode getTag(String tagName, String attrName, String attrValue) {
		for(XMLNode tag : body) {
			if(tag.name.equalsIgnoreCase(tagName)) {
				String eAttrValue = tag.attr.get(attrName);
				if(eAttrValue != null && eAttrValue.equalsIgnoreCase(attrValue))
					return tag;
			}
		}
		return null;
	}
	public String toString() {
		StringBuilder b = new StringBuilder("<");
		b.append(name);
		for(String attrName : attr.keySet()) {
			String attrValue = attr.get(attrName);
			b.append(" ").append(attrName).append("=").append(attrValue);
		}
		b.append(">");
		for(XMLNode tag : body)
			b.append(tag.toString());
		b.append("</").append(name).append(">");
		return b.toString();
	}
}
